<template>
  <t-upload
    ref="uploadRef1"
    :action="url"
    :headers="headers"
    theme="image"
    accept="image/*"
    @success="onSuccess"
    @remove="onRemove"
    :default-files="defaultFiles"
    :locale="{
      triggerUploadText: {
        image: '请选择图片',
      },
    }"
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useUserStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';

const props = defineProps<{
  image?: string | null;
}>();

const emit = defineEmits(['update:image', 'success']);

const userStore = useUserStore();
const url = import.meta.env.VITE_API_URL_PREFIX + '/common/upload';
const headers = {
  Authorization: 'Bearer ' + userStore.token,
};

// 将传入的 image URL 转换为 t-upload 所需的 default-files 格式
const defaultFiles = computed(() => {
  if (!props.image) return [];
  return [{ url: import.meta.env.VITE_PROXY_API_URL + props.image }];
});

const onSuccess = (res: any) => {
  const imageUrl = res.response.fileName;
  emit('update:image', imageUrl);
  emit('success', imageUrl);
  MessagePlugin.success('上传成功');
};

const onRemove = () => {
  emit('update:image', ''); // 清空图片
  MessagePlugin.success('图片已删除');
};
</script>
